import { createRouter, createWebHistory } from 'vue-router';
import Login from '../components/Login.vue';
import Profile from '../components/Profile.vue';
import Favorites from '../components/Favorites.vue';
import FollowList from '../components/FollowList.vue';
import PasswordResetRequest from '../components/PasswordResetRequest.vue';
import PasswordReset from '../components/PasswordReset.vue';
import CourseDetail from '../components/CourseDetail.vue'
import CoursePlatformHomepage from "@/components/CoursePlatformHomepage.vue";

const routes = [
  { path: '/login', component: Login },
  { path: '/profile', component: Profile },            // 需要登录保护
  { path: '/favorites', component: Favorites },        // 需要登录保护
  { path: '/follow-list', component: FollowList },     // 需要登录保护
  { path: '/coursePlatformHomepage',component: CoursePlatformHomepage},
  { path: '/course/:id',component: CourseDetail},
  { path: '/request-reset', component: PasswordResetRequest }, // 不受保护页面，密码重置请求页面
  { path: '/reset-password', component: PasswordReset },       // 不受保护页面，重置密码页面
  { path: '/', redirect: '/login' }  // 默认重定向到登录页面
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const loggedInUser = sessionStorage.getItem('userProfile'); // 获取用户登录信息
  const publicPages = ['/login', '/request-reset', '/reset-password']; // 不需要登录的页面
  const authNotRequired = publicPages.includes(to.path); // 判断页面是否不需要登录

  // 如果页面不需要身份验证，或者用户已经登录，允许继续访问
  if (authNotRequired || loggedInUser) {
    next(); // 继续访问
  } else {
    // 如果用户没有登录，且尝试访问受保护的页面，重定向到登录页面
    next('/login');
  }
});

export default router;